package com.tonyspace.web;

import com.tonyspace.constant.WxService;
import com.tonyspace.utils.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;



/**
 * @author: dell
 * @Date: 15:31 2018/11/23
 * @Description:
 */
@Api(tags={"用户接口"})
@RestController
@RequestMapping(value = "/testWechat")
public class WechatAuthController {
    private String starAppId="";
    private String starSecret="";

    private String wantechAppId = "";
    private String wantechSecret = "";


    /**
     * 从微信中发起网页授权
     */
    @ApiOperation(value = "发起用户授权")
    @RequestMapping(value = "/oauth2code" , method = RequestMethod.GET)
    public void getOauth2Code(HttpServletResponse response) throws UnsupportedEncodingException {
        String url = CommonUtils.getOautho2AuthorizeUrl(starAppId,WxService.CODE_CALLBACK_URL);
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ;
    }

    @ApiOperation(value = "授权回调")
    @RequestMapping(value = "/codecallback" , method = RequestMethod.GET)
    public String codeCallback(HttpServletRequest request){
        String code = request.getParameter("code");
        String state = request.getParameter("state");

        String url = CommonUtils.getOauth2AcessTokenUrl(starAppId,starSecret,code);
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = client.execute(httpGet);
            String value = httpResponse.getEntity().toString();
            return value;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "nothing";
    }


}
